﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Data = System.Windows.Data;

namespace Huyn.MultiBinding
{


    public static class DataContextWatcher
    {

        // Using a DependencyProperty as the backing store for DataContextLinker.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DataContextLinkerProperty =
            DependencyProperty.Register("DataContextLinker", typeof(object), typeof(FrameworkElement), new PropertyMetadata(null, DataContextLinkerCallback));

        private static void DataContextLinkerCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var callback=GetDataContextCallbackAttached(d);
            if (callback != null)
            {
                callback(e);
            }
        }

        internal static void Watch(FrameworkElement targetItem,Action<DependencyPropertyChangedEventArgs> callback)
        {
            SetDataContextCallbackAttached(targetItem,callback);
            targetItem.SetBinding(DataContextLinkerProperty, new Data.Binding());
        }

        #region DataContextCallbackAttached

        public static readonly DependencyProperty DataContextCallbackAttachedProperty =
            DependencyProperty.RegisterAttached("DataContextCallbackAttached",
                typeof(Action<DependencyPropertyChangedEventArgs>), typeof(MultiBindingLinker), new PropertyMetadata(null));

        public static Action<DependencyPropertyChangedEventArgs> GetDataContextCallbackAttached(DependencyObject obj)
        {
            return (Action<DependencyPropertyChangedEventArgs>)obj.GetValue(DataContextCallbackAttachedProperty);
        }

        public static void SetDataContextCallbackAttached(DependencyObject obj, Action<DependencyPropertyChangedEventArgs> value)
        {
            obj.SetValue(DataContextCallbackAttachedProperty, value);
        }
        #endregion
    }
}
